<template>
	<view class="customer-list-page">
		<!-- 搜索和筛选 -->
		<view class="search-section">
			<uni-easyinput v-model="searchKeyword" type="search" placeholder="请输入电话号码与名字查询"
				@confirm="handleSearch"></uni-easyinput>
		</view>
		<view class="uni-padding-wrap uni-common-mt">
			<uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" />
		</view>
		<!-- 客户列表 -->
		<view id="content" class="content">
			<scroll-view class="customer-list" scroll-y="true" @scrolltolower="loadMore" :style="{height:height}">
				<!-- <view class="customer-item" v-for="customer in displayedCustomers" :key="customer._id"
					@click="viewCustomerDetail(customer)">
					<view class="customer-info">
						<view class="customer-header">
							<text class="customer-name">{{ customer.customerName }}</text>
							<text class="customer-status-tag status-1" v-if="customer.isSchedule">
								已报备
							</text>
							<text v-else class="customer-status-tag status-2">
								未报备
							</text>
						</view>
						<text class="customer-phone" v-if="customer.zhongjieId">中介：{{ customer.zhongjieName }}</text>
						<text class="customer-phone"
							v-if="customer.consultantName">顾问：{{ customer.consultantName }}</text>
						<text class="customer-phone">{{ customer.phone }}</text>
						<text class="customer-last-contact">最后联系: {{ formatLastContact(customer.lastContact) }}</text>
						<text class="customer-source">来源: {{ getSourceTypeText(customer.typeMap) }}</text>
					</view>
					<view class="customer-actions">
						<view class="action-btn contact" @tap.stop="contactCustomer(customer)">联系</view>
						<view class="action-btn history" v-if="customer.isSchedule == 0"
							@tap.stop="scheduleVisit(customer)">报备</view>
					</view>
				</view> -->
				<view class="customer-list">
					<view class="customer-item" v-for="customer in displayedCustomers" :key="customer._id"
						@click="viewCustomerDetail(customer)">
						<view class="customer-info">
							<view class="customer-header">
								<text class="customer-name">{{ customer.customerName }}</text>
								<text class="customer-status-tag" :class="customer.statusClass">
									{{ $getStatusText(customer.status) }}
								</text>
							</view>
							<text class="customer-phone" v-if="customer.zhongjieId">中介：{{ customer.zhongjieName }}</text>
							<text class="customer-phone">{{ customer.phone }}</text>
							<text class="customer-phone" v-if="Array.isArray(customer.otherPhones) && customer.otherPhones.length">{{ customer.otherPhones.toString() }}</text>
							<text class="customer-last-contact">最后联系: {{ formatLastContact(customer.lastContact) }}</text>
							<text class="customer-source">来源: {{ getSourceTypeText(customer.typeMap) }}</text>
							<text class="customer-source" v-if="customer.status<=12">过期时间:
								{{$formatTime(customer.expriteTime)}}</text>
						</view>
					</view>
				</view>

				<!-- 加载更多 -->
				<view class="load-more" v-if="loading">
					<text>加载中...</text>
				</view>
				<view class="no-more" v-if="!hasMore && displayedCustomers.length > 0">
					<text>没有更多数据了</text>
				</view>
				<view class="no-data" v-if="!loading && displayedCustomers.length === 0">
					<text>暂无客户数据</text>
				</view>
			</scroll-view>


		</view>
		<!-- 添加客户按钮 -->
		<!-- <view class="floating-btn" @click="addNewCustomer">
      <text class="btn-icon">+</text>
    </view> -->
	</view>
</template>

<script>
	export default {
		data() {
			return {
				searchKeyword: '',
				filterLevel: 'all',
				loading: false,
				hasMore: true,
				pageNo: 1,
				pageSize: 10,
				displayedCustomers: [],
				total: 0,
				type: 0,
				height: '500px',
				items: ['老客户待跟进', '新客户带处理', '来访待处理'],
				current: 0
			}
		},

		onLoad(query) {
			if (query.type) {
				this.type = 11
			}
			this.loadCustomers()
		},
		mounted() {
			this.$nextTick(function() {
				setTimeout(() => {
					uni.getSystemInfo({
						success: (resu) => {
							const query = uni.createSelectorQuery()
							query.select('#content').boundingClientRect()
							query.exec(res => {
								this.height = resu.windowHeight - res[0].top - 30+
									'px';
							})
						},
						fail: (res) => {}
					})
				}, 100)
			})
		},
		methods: {
			onClickItem(e) {
				if (this.current != e.currentIndex) {
					this.current = e.currentIndex;
					this.pageNo = 1
					this.displayedCustomers = []
					this.loadCustomers()
				}
			},
			// 获取客户来源文本
			getSourceTypeText(type) {
				const typeMap = {
					1: '自然到访',
					2: '中介推荐',
					3: '老客户推荐',
					4: '线上渠道'
				}
				return typeMap[type] || '自然到访'
			},
			// 加载客户数据
			async loadCustomers() {
				if (this.loading) return

				this.loading = true
				try {
					 let postData = {
						 userId: this.$userInfo._id,
						 pageSize: 10,
						 keyword:this.searchKeyword,
						 pageNo:this.pageNo,
						 isRegistration:1
					 }
					 
					 let current = this.current 
					 switch (current){
					 	case 0:
							postData = {
								userId: this.$userInfo._id,
								expirteDay:3,
								pageSize: 10,
								keyword:this.searchKeyword,
								pageNo:this.pageNo
								
							}
					 		break;
						case 1:
							postData = {
								userId: this.$userInfo._id,
								completionRate:0,
								pageSize: 10,
								keyword:this.searchKeyword,
								pageNo:this.pageNo
							}	
					 	default:
					 		break;
					 }
					//带接待的客户
					const res = await this.$cloudOBjAjax('suuny-custom', 'getZYGWcustomer', {
						...postData
					})
					if(Array.isArray(res.list)){
						res.list.map(item => {
							item.statusClass = this.getStatusClass(item.status)
							return item
						})
					}
					if (this.pageNo === 1) {
						// 第一页，直接替换数据
						this.displayedCustomers = res.list
					} else {
						// 加载更多，追加数据
						this.displayedCustomers = [...this.displayedCustomers, ...data.list]
					}

					this.total = res.total
					this.hasMore = res.hasNext

					// 如果没有数据且不是第一页，说明没有更多了
					if (res.list.length === 0 && this.pageNo > 1) {
						this.hasMore = false
					}

				} catch (error) {
					console.error('加载客户数据失败:', error)
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					})

					// 开发环境下使用模拟数据
				} finally {
					this.loading = false
				}
			},
			// 搜索处理
			handleSearch() {
				this.pageNo = 1
				this.hasMore = true
				this.loadCustomers()
			},
			// 格式化最后联系时间
			formatLastContact(timeStr) {
				if (!timeStr) return '暂无联系记录'

				const time = new Date(timeStr)
				const now = new Date()
				const diff = now - time
				const days = Math.floor(diff / (1000 * 60 * 60 * 24))

				if (days === 0) {
					return '今天'
				} else if (days === 1) {
					return '昨天'
				} else if (days < 7) {
					return `${days}天前`
				} else {
					return timeStr.split(' ')[0] // 只显示日期部分
				}
			},

			// 查看客户详情
			viewCustomerDetail(customer) {
				uni.navigateTo({
					url: `/pages/customer/detail?id=${customer._id}`
				})
			},

			// 联系客户
			contactCustomer(customer) {
				uni.makePhoneCall({
					phoneNumber: customer.phone
				})
			},

			// 加载更多
			loadMore() {
				if (this.hasMore && !this.loading) {
					this.pageNo++
					this.loadCustomers()
				}
			},
			getStatusClass(status) {
				return this.$statusMap[status]?.class || 'status-unknown'
			}
		}
	}
</script>

<style scoped lang="scss">
	.customer-list-page {
		background: #f5f6fa;
		display: flex;
		height: 100%;
		flex-direction: column;
		padding: 20rpx;
		box-sizing:border-box;
		// padding: 20rpx;
	}

	.content {
		padding: 20rpx;
	}
	
	.uni-padding-wrap {
		margin: 20rpx;
	}

	.search-section {
		background: white;
		border-radius: 16rpx;
		padding: 20rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
		flex-shrink: 0;
		margin: 0rpx;
	}

	.customer-list {
		display: flex;
		gap: 30rpx;
		white-space: nowrap;
		flex-direction: column;
		
	}
	
	.customer-item {
		display: flex;
		align-items: center;
		background: white;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
	}
	
	.customer-info {
		flex: 1;
	}
	
	.customer-header {
		display: flex;
		align-items: center;
		gap: 10px;
		margin-bottom: 8rpx;
	}
	
	.customer-name {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
	}
	
	.customer-tag {
		padding: 6rpx 16rpx;
		border-radius: 12rpx;
		font-size: 20rpx;
	
		&.high {
			background: #ff4757;
			color: white;
		}
	
		&.medium {
			background: #ffa502;
			color: white;
		}
	
		&.low {
			background: #dfe4ea;
			color: #666;
		}
	}
	
	.customer-phone {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 4rpx;
		display: block;
	}
	
	.customer-last-contact {
		font-size: 22rpx;
		color: #999;
		margin-bottom: 4rpx;
		display: block;
	}
	
	.customer-source {
		font-size: 22rpx;
		color: #888;
		display: block;
	}
	
	.customer-actions {
		margin-left: 20rpx;
	}

	.btn-icon {
		color: white;
		font-size: 40rpx;
		font-weight: bold;
	}

	.load-more,
	.no-more,
	.no-data {
		text-align: center;
		padding: 30rpx;
		color: #999;
		font-size: 24rpx;
	}
	
	.customer-status-tag {
		padding: 6rpx 16rpx;
		border-radius: 12rpx;
		font-size: 20rpx;
		font-weight: 500;
	
		/* 不同状态的样式 */
		&.status-1 {
			background: #e6f7ff;
			color: #1890ff;
			border: 1rpx solid #91d5ff;
		}
	
		&.status-2 {
			background: #f6ffed;
			color: #52c41a;
			border: 1rpx solid #b7eb8f;
		}
	
		&.status-3 {
			background: #fff7e6;
			color: #fa8c16;
			border: 1rpx solid #ffd591;
		}
	
		&.status-41 {
			background: #fff2f0;
			color: #ff4d4f;
			border: 1rpx solid #ffccc7;
		}
	
		&.status-14 {
			background: #f9f0ff;
			color: #722ed1;
			border: 1rpx solid #d3adf7;
		}
	
		&.status-15 {
			background: #f6ffed;
			color: #52c41a;
			border: 1rpx solid #b7eb8f;
		}
	
		&.status-unknown {
			background: #fafafa;
			color: #8c8c8c;
			border: 1rpx solid #d9d9d9;
		}
	}
</style>